<template>
   <div class="app-container" v-loading="loading">
      <el-row :gutter="20">
         <!--部门数据-->
         <el-col :span="4" :xs="24">
            <div>
               <el-input v-model="deptName" placeholder="请输入组织机构名称" clearable prefix-icon="Search"
                  style="margin-bottom: 20px" />
            </div>
            <div>
               <el-tree :data="deptOptions" :props="{ label: 'name', children: 'children' }"
                  :expand-on-click-node="false" :filter-node-method="filterNode" ref="deptTreeRef" node-key="id"
                  :current-node-key="currentDeptKey" highlight-current default-expand-all
                  @node-click="handleNodeClick" />
            </div>
         </el-col>
         <!--用户数据-->
         <el-col :span="20" :xs="24">
            <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
               <el-form-item label="账号名" prop="userName">
                  <el-input v-model="queryParams.userName" placeholder="请输入账号名" clearable style="width: 240px"
                     @keyup.enter="handleQuery" />
               </el-form-item>
               <el-form-item label="手机号码" prop="mobile">
                  <el-input v-model="queryParams.mobile" placeholder="请输入手机号码" clearable style="width: 240px"
                     @keyup.enter="handleQuery" />
               </el-form-item>
               <el-form-item label="状态" prop="isActive">
                  <el-select v-model="queryParams.isActive" placeholder="用户状态" clearable style="width: 240px">
                     <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                  </el-select>
               </el-form-item>
               <el-form-item label="部门范围" prop="leafDept">
                  <el-select v-model="queryParams.leafDept" placeholder="是否包含子部门" clearable style="width: 240px">
                     <el-option :key="true" label="包含子部门" :value="true" />
                     <el-option :key="false" label="不包含子部门" :value="false" />
                  </el-select>
               </el-form-item>
               <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
               </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
               <el-col :span="1.5">
                  <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasFunc="'user:add'">新增</el-button>
               </el-col>
               <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
            </el-row>

            <el-table v-loading="userLoading && !loading" :data="userList" @selection-change="handleSelectionChange"
               highlight-current-row>
               <el-table-column type="selection" width="50" align="center" />
               <!-- <el-table-column label="用户编号" align="center" key="id" prop="id" v-if="columns.showColumn('id')" /> -->
               <el-table-column label="账号名" align="center" key="userName" prop="userName"
                  v-if="columns.showColumn('userName')" :show-overflow-tooltip="true" />
               <el-table-column label="昵称" align="center" key="nickName" prop="nickName"
                  v-if="columns.showColumn('nickName')" :show-overflow-tooltip="true" />
               <el-table-column label="归属部门" align="center" key="deptName" prop="department.name"
                  v-if="columns.showColumn('deptName')" :show-overflow-tooltip="true" />
               <el-table-column label="岗位" align="center" key="post" prop="post.name"
                  v-if="columns.showColumn('postName')" :show-overflow-tooltip="true" />
               <el-table-column label="手机号码" align="center" key="mobile" prop="mobile"
                  v-if="columns.showColumn('mobile')" width="120" />
               <el-table-column label="性别" align="center" key="gender" prop="gender" v-if="columns.showColumn('gender')"
                  width="120">
                  <template #default="scope">
                     <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
                  </template>
               </el-table-column>
               <el-table-column label="锁定状态" align="center" key="isLocked" v-if="columns.showColumn('isLocked')">
                  <template #default="{ row }">
                     <el-tag :type="(row.security?.isLocked ?? row.isLocked) ? 'danger' : 'success'" effect="plain">
                        {{ row.security?.isLocked ? '已锁定' : '正常' }}
                     </el-tag>
                  </template>
               </el-table-column>

               <el-table-column label="状态" align="center" key="isActive" v-if="columns.showColumn('isActive')">
                  <template #default="scope">
                     <el-switch v-model="scope.row.isActive" @change="handleStatusChange(scope.row)"></el-switch>
                  </template>
               </el-table-column>
               <el-table-column label="创建方式" align="center" prop="creationSource" :show-overflow-tooltip="true"
                  v-if="columns.showColumn('creationSource')">
                  <template #default="scope">
                     <dict-tag :options="user_creation_source" :value="scope.row.creationSource" />
                  </template>
               </el-table-column>
               <el-table-column label="创建时间" align="center" prop="createdAt" v-if="columns.showColumn('createdAt')"
                  width="160">
                  <template #default="scope">
                     <span>{{ parseTime(scope.row.createdAt) }}</span>
                  </template>
               </el-table-column>
               <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                  <template #default="scope">
                     <el-tooltip content="修改" placement="top" v-if="scope.row.id != 1">
                        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                           v-hasFunc="'user:edit'"></el-button>
                     </el-tooltip>
                     <el-tooltip content="删除" placement="top" v-if="scope.row.id != 1">
                        <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                           v-hasFunc="'user:del'"></el-button>
                     </el-tooltip>
                     <el-tooltip content="重置密码" placement="top" v-if="scope.row.id != 1">
                        <el-button link type="primary" icon="Key" @click="handleResetPwd(scope.row)"
                           v-hasFunc="'user:resetPwd'"></el-button>
                     </el-tooltip>
                     <el-tooltip content="分配角色" placement="top" v-if="scope.row.id != 1">
                        <el-button link type="primary" icon="CircleCheck" @click="handleAuthRole(scope.row)"
                           v-hasFunc="'user:edit'"></el-button>
                     </el-tooltip>
                     <el-tooltip content="解除锁定" placement="top"
                        v-if="scope.row.id != 1 && scope.row.security?.isLocked">
                        <el-button link type="primary" icon="unlock" @click="handleUnlock(scope.row)"
                           v-hasFunc="'user:unlock'"></el-button>
                     </el-tooltip>
                  </template>
               </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageIndex"
               v-model:limit="queryParams.pageSize" @pagination="getList" />
         </el-col>
      </el-row>

      <!-- 添加或修改用户配置对话框 -->
      <el-dialog :title="title" v-model="open" width="600px" destroy-on-close align-center draggable
         :close-on-click-modal="false">
         <el-tabs v-model="tabIndex">
            <el-tab-pane label="基本信息" name="baseInfo">
               <UserBase v-model="form" :depts="deptOptions" ref="baseFormRef" />
            </el-tab-pane>
            <el-tab-pane label="授权信息" name="roleGrant">
               <RoleGrant v-model="form.roleIds" :data="roleOptions" />
            </el-tab-pane>
         </el-tabs>

         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>

      <!-- 用户导入对话框 -->
      <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body destroy-on-close>
         <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
               <div class="el-upload__tip text-center">
                  <div class="el-upload__tip">
                     <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                  </div>
                  <span>仅允许导入xls、xlsx格式文件。</span>
                  <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                     @click="importTemplate">下载模板</el-link>
               </div>
            </template>
         </el-upload>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitFileForm">确 定</el-button>
               <el-button @click="upload.open = false">取 消</el-button>
            </div>
         </template>
      </el-dialog>

      <!-- 角色分配框 -->
      <el-dialog :title="roleDialogState.title" v-model="roleDialogState.show" width="500px" append-to-body draggable>
         <el-form ref="roleRef" label-width="80px" style="height: 300px;">
            <el-row>
               <el-col :span="24">
                  <el-checkbox-group v-model="roleDialogState.roleCheckedList">
                     <el-checkbox v-for="item in roleDialogState.roleList" :key="item.id" :label="item.name"
                        :value=item.id />
                  </el-checkbox-group>
               </el-col>
            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitRoleForm">确 定</el-button>
               <el-button @click="cancelRoleForm">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="User">
import { getToken } from "@/utils/auth";
import { changeUserStatus, listUser, resetUserPwd, delUser, getUser, updateUser, addUser, unlockUser } from "@/api/system/user";
import { treeDeptList } from "@/api/system/dept";
import { listRole } from "@/api/system/role";
import { saveSysUserRole } from "@/api/system/userrole";
import UserBase from "./components/baseInfo.vue"
import RoleGrant from "./components/roleGrant.vue"

const router = useRouter();
const { proxy } = getCurrentInstance();
//字典数据
const dicts = ["sys_normal_disable", "sys_user_sex", "user_creation_source"];
const dictRefs = proxy.useDict(...dicts);
const { sys_normal_disable, sys_user_sex, user_creation_source } = dictRefs;

const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const userLoading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const deptName = ref("");
const deptOptions = ref();
const roleOptions = ref([]);
const deptTreeRef = ref();
const currentDeptKey = ref();
const baseFormRef = ref();
const tabIndex = ref("baseInfo")
/*** 用户导入参数 */
const upload = reactive({
   // 是否显示弹出层（用户导入）
   open: false,
   // 弹出层标题（用户导入）
   title: "",
   // 是否禁用上传
   isUploading: false,
   // 是否更新已经存在的用户数据
   updateSupport: 0,
   // 设置上传的请求头部
   headers: { Authorization: "Bearer " + getToken() },
   // 上传的地址
   url: import.meta.env.VITE_APP_BASE_API + "/system/user/importData"
});
// 列显隐信息
const columns = ref([
   // { key: 0, label: `用户编号`, visible: true },
   { prop: "userName", label: `账号名`, visible: true },
   { prop: "nickName", label: `昵称`, visible: true },
   { prop: "deptName", label: `归属部门`, visible: true },
   { prop: "postName", label: `岗位`, visible: true },
   { prop: "mobile", label: `手机号码`, visible: true },
   { prop: "gender", label: `性别`, visible: true },
   { prop: "isLocked", label: `锁定状态`, visible: true },
   { prop: "isActive", label: `状态`, visible: true },
   { prop: "creationSource", label: `创建方式`, visible: true },
   { prop: "createdAt", label: `创建时间`, visible: true }
]);

const roleDialogState = reactive({
   show: false,
   title: "分配角色",
   userId: undefined,
   roleList: [],
   roleCheckedList: []
})


const data = reactive({
   form: {},
   queryParams: {
      pageIndex: 1,
      pageSize: 10,
      userName: undefined,
      mobile: undefined,
      isActive: true,
      deptId: undefined,
      leafDept: true
   },
});

const { queryParams, form } = toRefs(data);

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
   if (!value) return true;
   return data.name.includes(value);
};

/** 根据名称筛选归属部门树 */
watch(deptName, val => {
   deptTreeRef.value.filter(val);
});

/** 查询归属部门下拉树结构 */
function getDeptTree() {
   let treeParams = { isActive: true }
   return treeDeptList(treeParams).then(response => {
      deptOptions.value = response;
      return response;
   }).finally(res => {
   });
};

/** 查询用户列表 */
function getList() {
   userLoading.value = true;
   return listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
      const { result, totalNum } = res;
      userLoading.value = false;
      userList.value = result;
      total.value = totalNum;
   });
};

/** 节点单击事件 */
function handleNodeClick(data) {
   queryParams.value.deptId = data.id;
   handleQuery();
   currentDeptKey.value = data.id;
};

/** 搜索按钮操作 */
function handleQuery() {
   queryParams.value.pageIndex = 1;
   getList();
};

/** 重置按钮操作 */
function resetQuery() {
   dateRange.value = [];
   proxy.resetForm("queryRef");
   queryParams.value.deptId = undefined;
   deptTreeRef.value.setCurrentKey(null);
   handleQuery();
};

/** 删除按钮操作 */
function handleDelete(row) {
   const userIds = row.id || ids.value;
   proxy.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
      return delUser(userIds);
   }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
   }).catch(() => { });
};

/** 导出按钮操作 */
function handleExport() {
   proxy.download("system/user/export", {
      ...queryParams.value,
   }, `user_${new Date().getTime()}.xlsx`);
};

/** 用户状态修改  */
function handleStatusChange(row) {
   let text = row.isActive ? "启用" : "停用";
   proxy.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗?').then(function () {
      return changeUserStatus(row.id, row.isActive);
   }).then(() => {
      proxy.$modal.msgSuccess(text + "成功");
   }).catch(function () {
      row.isActive = !row.isActive;
   });
};

/** 更多操作 */
function handleCommand(command, row) {
   switch (command) {
      case "handleResetPwd":
         handleResetPwd(row);
         break;
      case "handleAuthRole":
         handleAuthRole(row);
         break;
      default:
         break;
   }
};

/** 跳转角色分配 */
function handleAuthRole(row) {
   tabIndex.value = "roleGrant";
   reset();
   const userId = row.id || ids.value;
   getUser(userId).then(response => {
      form.value = response;
      open.value = true;
      title.value = "编辑账号";
   });
};

/** 重置密码按钮操作 */
function handleResetPwd(row) {
   proxy.$modal.confirm(`确认重置用户"${row.userName}"的密码？`).then(function () {
      return resetUserPwd(row.id)
   }).then((res) => {
      proxy.$modal.msgSuccess("重置成功，新密码是：" + res);
   }).catch(() => { });
};

/** 解锁按钮操作 */
const handleUnlock = (row) => {
   return unlockUser(row.id).then(() => {
      proxy.$modal.msgSuccess("解锁成功");
      getList();
   });
};


/** 选择条数  */
function handleSelectionChange(selection) {
   ids.value = selection.map(item => item.id);
   single.value = selection.length != 1;
   multiple.value = !selection.length;
};


/** 下载模板操作 */
function importTemplate() {
   proxy.download("system/user/importTemplate", {
   }, `user_template_${new Date().getTime()}.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
   upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
   upload.open = false;
   upload.isUploading = false;
   proxy.$refs["uploadRef"].handleRemove(file);
   proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
   getList();
};

/** 提交上传文件 */
function submitFileForm() {
   proxy.$refs["uploadRef"].submit();
};

/** 重置操作表单 */
function reset() {
   form.value = {
      id: undefined,
      deptId: currentDeptKey.value,
      userName: undefined,
      nickName: undefined,
      mobile: undefined,
      email: undefined,
      localEmail: true,
      sex: undefined,
      isLocked: false,
      remark: undefined,
      postIds: [],
      roleIds: []
   };
   proxy.resetForm("userRef");
};

/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
};

/** 新增按钮操作 */
function handleAdd() {
   reset();
   open.value = true;
   tabIndex.value = "baseInfo";
   title.value = "新增账号";
};

/** 修改按钮操作 */
function handleUpdate(row) {
   tabIndex.value = "baseInfo";
   reset();
   const userId = row.id || ids.value;
   getUser(userId).then(response => {
      form.value = response;
      open.value = true;
      title.value = "编辑账号";
   });
};

/** 提交按钮 */
function submitForm() {
   baseFormRef.value.validate().then(res => {
      if (form.value.id != undefined) {
         updateUser(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
         });
      } else {
         addUser(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
         });
      }
   }).catch(res => {
      console.log(res);
      proxy.$modal.msgWarning("请检查数据完整性")
   })
};

function submitRoleForm() {
   let data = { userId: roleDialogState.userId, roleId: roleDialogState.roleCheckedList }
   saveSysUserRole(data).then(res => {
      resetRoleDialogState();
   })
}

function cancelRoleForm() {
   resetRoleDialogState();
}

function resetRoleDialogState() {
   roleDialogState.show = false;
   roleDialogState.roleCheckedList = [];
   roleDialogState.roleList = [];
   roleDialogState.userId = undefined;
}

const getRoleList = () => {
   listRole({ pageSize: 999, isActive: true }).then(({ result }) => {
      roleOptions.value = result;
   })
}

const init = () => {
   loading.value = true;
   getDeptTree().then(res => {
      let first = res[0];
      queryParams.value.deptId = first.id;
      currentDeptKey.value = first.id;
      return getList();
   }).finally(() => {
      loading.value = false;
   })
   getRoleList();
}

init();

</script>
